﻿using System.Collections.Generic;
using BitBenderGames;
using Gameplay.PVE.Utils;
using UnityEngine;
using Yoozoo.Framework.Managers;
using Yoozoo.Gta.Common;

namespace Gameplay.PVE
{
    public class ModelDrag : MonoBehaviour
    {
        public GameObject levelObj;
        public int HeroId;
        public Vector3[] DeckCirclePosArray;
        public bool isLoading = true;
        public int curPosIdx = -1;
        public int oldPosIdx = -1;

        private Vector3 startPos;
        private Vector3 lastPos;
        private Vector3 offset;
        public bool isDragging = false;

        private float touchY;
        private float touchX;

        private Vector3 startTouchPos;
        private Vector3 lastTouchPos;

        private int lastTouchFingerId;
        
        private bool isTouchEmpty = false;

        private float dragDistance = 0;
        

        private Dictionary<int, int> fingerDic = new Dictionary<int, int>();//key fingerId， value touchIndex

        private class TouchData
        {
            public ETouchState touchState;
            public Vector3 lastTouchPosition;
        }
        
        private enum ETouchState
        {
            None,
            Touch,
            Drag,
        }
        
        private void UpdateTouchState()
        {
            /*foreach (var item in fingerDic.Keys)
            {
                fom
            }
            for (int i = 0; i < TouchWrapper.Touches)
            TouchWrapper.Touches[0].FingerId*/
        }
        
        
        public void OnUpdate()
        { 
            // 新手引导 强引导期间 不可拖动
            if (TouchWrapper.TouchCount == 0)
            {
                isTouchEmpty = false;
            }
            //如果没有点击到模型，直接返回
            if (TouchWrapper.TouchCount > 0 && !isDragging)
            {
                RaycastHit raycastHit = new RaycastHit();
                Ray ray = PveCameraManager.Instance.mainCamera.ScreenPointToRay(new Vector3(
                    TouchWrapper.Touch0.Position.x,
                    TouchWrapper.Touch0.Position.y, 0f));
                bool hasHit = Physics.Raycast(ray, out raycastHit, Mathf.Infinity,PveUtils.pveLogicLayer);
                ModelDrag drag = raycastHit.transform.gameObject.GetComponent<ModelDrag>();
                if (!hasHit || drag == null || drag.HeroId != HeroId)
                {
                    isTouchEmpty = true;
                    return;
                }

                if (isTouchEmpty)
                {
                    return;
                }
                var startPosition = ray.origin -(ray.origin.z - raycastHit.transform.position.z) / ray.direction.z * ray.direction;
                touchY = startPosition.y;// - raycastHit.transform.position.y;
                touchX = startPosition.x - raycastHit.transform.position.x;
                startTouchPos = TouchWrapper.Touch0.Position;
                lastTouchPos = startTouchPos;
                isTouchEmpty = false;
                lastTouchFingerId = TouchWrapper.Touch0.FingerId;
            }
            //拖动开始逻辑
            if (TouchWrapper.TouchCount > 0 && TouchWrapper.Touch0.FingerId == lastTouchFingerId && !isDragging && !DeckManager.Instance.isDragging)
            {
                DeckManager.Instance.isDragging = true;
                DeckManager.Instance.curModelDrag = this;
                isDragging = true;
                oldPosIdx = curPosIdx;
                startPos = transform.position;
                //offset = transform.position - startTouchPosition;
                lastTouchPos = TouchWrapper.Touch0.Position;
            }
            //拖动中逻辑
            else if (TouchWrapper.TouchCount > 0 && TouchWrapper.Touch0.FingerId == lastTouchFingerId && isDragging)
            {
                dragDistance += Vector3.Distance(lastTouchPos, TouchWrapper.Touch0.Position);
                lastTouchPos = TouchWrapper.Touch0.Position;
                var groundPosition = GetGroundPositionByScreenPosition(TouchWrapper.Touch0.Position);
                transform.position = groundPosition - new Vector3(touchX,touchY -0.01f,0);
                int newPos = DeckManager.Instance.UpdateCircle(transform.position, curPosIdx);
                // 判断拖拽交换位置
                if (newPos != curPosIdx && newPos >= 0)
                {
                    DeckManager.Instance.SwitchModelPos(transform.position, HeroId);
                    DeckManager.Instance.PrintDeckInfo();
                }
                else if (newPos < 0)
                {
                    DeckManager.Instance.RestoreOldPos(false);
                    // 还原拖拽的字典记录
                    DeckManager.Instance.UpdateHeroToDeckPosDict(HeroId, oldPosIdx);
                    DeckManager.Instance.UpdateHasDeckSpace(oldPosIdx, HeroId);
                    DeckManager.Instance.PrintDeckInfo();
                }
                curPosIdx = newPos;
            }
            else
            {
                //拖动结束逻辑
                if (isDragging)
                {
                    isDragging = false;
                    DeckManager.Instance.isDragging = false;
                    DeckManager.Instance.ResetCircleColor();
                    //var dist = Vector3.Distance(lastTouchPos, startTouchPos);
              
                    if (dragDistance < 15) 
                    {
                        transform.position = startPos;
                        ResidentHandler.Inst.GetFunction("pveManager.CancelDeckModel").Action(HeroId);
                        DeckManager.Instance.UpdateHasDeckSpace(oldPosIdx, -1);
                        return;
                    }


                    int resetIdx = curPosIdx;
                    bool bIsInScreen = IsMouseInScreen();
                    // 判断当前位置有效
                    if (curPosIdx >= 0 && bIsInScreen)
                    {
                        // 有效 设置拖拽模型位置
                        DeckManager.Instance.UpdateDeckModelPos(HeroId, curPosIdx);
                        DeckManager.Instance.UpdateHeroToDeckPosDict(HeroId, curPosIdx);
                        DeckManager.Instance.RestoreOldPos(true);
                        DeckManager.Instance.PrintDeckInfo();
                    }
                    else
                    {
                        // 无效 还原拖拽模型位置
                        resetIdx = oldPosIdx;
                        DeckManager.Instance.RestoreOldPos(false);
                        DeckManager.Instance.PrintDeckInfo();
                        
                    }
                    DeckManager.Instance.PlayCircleAni(resetIdx, "ani_sfx_buzheng_down");
                    DeckManager.Instance.RefreshAllColor();
                }
                lastTouchFingerId = 0;
                dragDistance = 0;
            }
        }

        private bool IsMouseInScreen()
        {
#if (UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR
            return true;
#else
            float x = Input.mousePosition.x;
            float y = Input.mousePosition.y;
            return x > 0 && x < Screen.width && y > 0 && y < Screen.height;
#endif
        }

        private void AttachDrag()
        {
            for (int i = 0; i < DeckCirclePosArray.Length; i++)
            {
                float dot = Vector3.Dot(Vector3.Normalize(transform.position - lastPos),
                    Vector3.Normalize(DeckCirclePosArray[i] - lastPos));
                float dis = Vector3.Distance(DeckCirclePosArray[i], transform.position);
                if (dot > 0.9 && dis < 1.5f && dis > 0.5f)
                {
                    transform.position = DeckCirclePosArray[i];
                }
            }
        }

        private Vector3 GetGroundPositionByScreenPosition(Vector2 pos)
        {
            Ray ray = PveCameraManager.Instance.mainCamera.ScreenPointToRay(new Vector3(pos.x, pos.y, 0f));
            var origin = ray.origin;
            var direction = ray.direction;
            var p = (origin.y - touchY) / direction.y;
            return origin - direction * p;
        }
    }
}
